package com.example.kwokg.meishi.Fragments;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.kwokg.meishi.Activity.VideoActivity;
import com.example.kwokg.meishi.Bean.Content;
import com.example.kwokg.meishi.Constants;
import com.example.kwokg.meishi.LoadJsonTask;
import com.example.kwokg.meishi.R;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

import static cn.bmob.v3.Bmob.getApplicationContext;


/**
 * A simple {@link Fragment} subclass.
 */
public class ContentFragment extends Fragment {

    private List<Content> contents=new ArrayList<>();
    private PullToRefreshGridView gv;
    private int page=1;
    private int count=10;
    private String content;
    private int contentId;
    private ContentAdapter adapter;

    public ContentFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_content, container, false);
    }

    @Override
    public void onViewCreated(final View view, @Nullable Bundle savedInstanceState) {
        gv = (PullToRefreshGridView) view.findViewById(R.id.gv);
        super.onViewCreated(view, savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle!=null){
            contentId = bundle.getInt("contentId");
            //初始化View
            initView();
            //得到内容Url获取数据
            getData();
        }
    }

    private void getData() {
        if (contentId==1){
            content = Constants.CONTENT_HOT;
        }else{
            content= String.format(Constants.CONTENT_URL,contentId,page,count);
        }
        new LoadJsonTask(new LoadJsonTask.onGetJsonResultListener() {
            @Override
            public void onGetJsonResult(Object result) {
                contents= (List<Content>) result;
                //拿到数据后对数据进行操作
                gv.onRefreshComplete();
                adapter.notifyDataSetChanged();
            }
        }, Constants.CONTENT).execute(content);
    }

    private void initView() {
        adapter = new ContentAdapter();
        gv.setAdapter(adapter);

        //刷新加时间
        String label = DateUtils.formatDateTime(
                getApplicationContext(),
                System.currentTimeMillis(),
                DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
        // Update the LastUpdatedLabel
        gv.getLoadingLayoutProxy().setLastUpdatedLabel(label);
        //刷新显示信息设置
        ILoadingLayout startLabels = gv.getLoadingLayoutProxy();
        startLabels.setPullLabel("下拉");// 刚下拉时，显示的提示
        startLabels.setRefreshingLabel("加载中...");// 刷新时
        startLabels.setReleaseLabel("松开");// 下来达到一定距离时，显示的提示
        //上下拉刷新
        gv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<GridView>() {

            @Override
            public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
                page++;
                getData();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
                count+=10;
                getData();
            }
        });

        //GridView条目点击事件
        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                startActivity(new Intent(getContext(), VideoActivity.class).putExtra("video",contents.get(position)));
                getActivity().overridePendingTransition(0,0);
            }
        });
    }

    //GridView内容适配器
    class ContentAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return contents==null?0:contents.size();
        }

        @Override
        public Object getItem(int position) {
            return contents==null?null:contents.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;
            if (convertView==null){
                convertView=LayoutInflater.from(getActivity()).inflate(R.layout.grid_item,parent,false);
                holder=new ViewHolder(convertView);
                convertView.setTag(holder);
            }else {
                holder= (ViewHolder) convertView.getTag();
            }

            Content content=contents.get(position);
            holder.title.setText(content.getRecommend_caption());
            holder.count.setText(String.valueOf(content.getLikes_count()));
            String iv=content.getCover_pic();
            String atr=content.getAvatar();
            Picasso.with(getActivity()).load(iv).into(holder.ivShow);
            Picasso.with(getActivity()).load(atr).into(holder.avatar);
            return convertView;
        }


        class ViewHolder{
            TextView title,count;
            ImageView ivShow,avatar;

            public ViewHolder(View view){
                title = (TextView) view.findViewById(R.id.item_title);
                count = (TextView) view.findViewById(R.id.item_count);
                ivShow = (ImageView) view.findViewById(R.id.item_iv);
                avatar = (ImageView) view.findViewById(R.id.item_avatar);
            }
        }
    }
}
